{% extends "subpage/base.html" %}
{% block title %}
    系统运维部
{% endblock %}
{% block scripts %}
    {{ super() }}
    <script type="text/javascript" charset="utf-8"
            src="{{ url_for('static', filename='ueditor/ueditor.config.js') }}"></script>
    <script type="text/javascript" charset="utf-8"
            src="{{ url_for('static', filename='ueditor/ueditor.all.min.js') }}"></script>
    <script type="text/javascript"
            src="{{ url_for("static",filename="extra/My97DatePicker/WdatePicker.js") }}"></script>
    <!--建议手动加在语言，避免在ie下有时因为加载语言失败导致编辑器加载失败-->
    <!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
    <script type="text/javascript" charset="utf-8"
            src="{{ url_for('static', filename='ueditor/lang/zh-cn/zh-cn.js') }}"></script>
    <script src="{{ url_for('static',filename='ueditor/ueditor.parse.js') }}"></script>
    <script>
        setTimeout(function () {
            uParse('div',
                {
                    'highlightJsUrl': '{{ url_for("static",filename="ueditor/third-party/SyntaxHighlighter/shCore.js") }}',
                    'highlightCssUrl': '{{ url_for("static",filename="ueditor/third-party/SyntaxHighlighter/shCoreDefault.css") }}'

                })
        }, 300);
    </script>
{% endblock %}
{% block styles %}
    <style>
        .input-items .control-label {
            width: 108px;
        }
    </style>
{% endblock %}
{% block table %}
    <div class="input-items clearfix">
        <div class="form-group clearfix">
            <div class="col-xs-12">
                <label for="selectPosition" class="col-xs-2 control-label"><i class="require">*</i>机房位置</label>
                <div class="col-xs-10">
                    <select name="selectPosition" id="selectPosition" class="form-control">

                    </select>
                </div>
            </div>
        </div>
        <div class="form-group clearfix">
            <div class="col-xs-6">
                <label for="inputBandwidth" class="col-xs-3 control-label"><i class="require">*</i>网络带宽</label>
                <div class="col-xs-9">
                    <input type="number" class="form-control" id="inputBandwidth" placeholder="网络带宽"/>
                </div>
            </div>
            <div class="col-xs-3 col-xs-offset-2">
                <div class="operate-add">
                    <button class="btn btn-primary operate-add-btn">添加</button>
                </div>
            </div>
        </div>


    </div>
    <div class="show-input-items clearfix">
        <table class="table table-bordered">
            <tbody>
            <tr>
                <th style="width: 50%">机房位置</th>
                <th>带宽值(Mb/s)</th>
                <th>操作</th>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            </tbody>
        </table>
    </div>
{% endblock %}
{% block time_field %}
    <div class="time_field">
        <label for="dutyTime" class="control-label col-xs-4" style="padding-top: 6px;padding-left: 0"><i
                class="require">*</i>日报时间</label>
        <div class="col-xs-8">
            <input type="text" id="dutyTime" class="Wdate"
                   onclick="WdatePicker({maxDate:'%y-%M-%d',dateFmt:'yyyy/MM/dd',alwaysUseStartDate:true})"/>
        </div>
    </div>
{% endblock %}
{% block ueditorbox %}

    <script id="editor" type="text/plain"></script>

    <div class="clearfix submit-box">
        <button type="button" class="btn btn-primary btn-submit-confirm pull-left">提交</button>
        <button type="button" class="btn btn-default pull-right cancel-return">取消</button>
    </div>

{% endblock %}
{% block content %}
    {{ super() }}
    <script>
        $(function () {
            var index = 0, trs = $('.table tbody tr').length, total = 0, departId = GetQueryString('departId'),
                title = GetQueryString('departAlias'), depart_id = GetQueryString('departId'), deleteArray = [],
                addArray = [],
                dutyId = GetQueryString('dutyId'), originalData;
            var ue = UE.getEditor('editor', {
                serverUrl: "/upload",
                initialFrameWidth: 880,  //初始化编辑器宽度,默认1000
                initialFrameHeight: 500
            });

            if (!dutyId) {//创建时
                ue.ready(function () {
                    //查询是否已存在模板
                    ajaxRequestJson("GET", GLOBAL_VARIABLE.BASE_URL + "/gettemplate", {"departId": depart_id}, success, error, "{{ csrf_token }}");
                    function success(data) {
                        if (data.code === 0) {
                            ue.setContent(data.data.tempText);

                        } else if (data.code === 1) {
                            $.myAlert({title: "出错提示", message: data.errmessage});
                        }
                    }

                    function error() {
                        $.myAlert({title: '出错提示', message: '请求出错！'});
                        return false;
                    }
                });
            } else if (dutyId) {
                ajaxRequest('GET', GLOBAL_VARIABLE.BASE_URL + '/datashow', {
                    "dutyId": GetQueryString("dutyId"),
                    "departId": GetQueryString("departId"),
                    "level": 2
                }, function (data) {
                    originalData = data.tableList;
                    $("#dutyTime").val(data.richTextTime);
                    ue.ready(function () {
                        ue.setContent(data.richText);
                    });
                    //给table赋值
                    toTableVal(originalData);
                }, function (error) {
                    $.myAlert({title: "出错啦", message: '请求出错！'});
                });

            }

            loadComputerRoom();

            function toTableVal(list) {
                console.log(list);
                if (list.length <= trs - 1) {
                    for (var i = 0; i < list.length; i++, index++, total++) {
                        var roomId = list[i].room_id, location = list[i].idc, bandWidth = list[i].bw,
                            bandId = list[i].band_id;
                        $('.table tbody tr').eq(i + 1).attr({
                            "data-roomid": roomId,
                            "data-bandid": bandId
                        }).html('<td>' + location + '</td><td>' + bandWidth + '</td><td class="text-center"><i class="fa fa-minus-circle remove-item"></i></td>');
                    }

                } else {
                    for (var j = 0; j < list.length; j++, index++, total++) {
                        var roomId = list[j].room_id, location = list[j].idc, bandWidth = list[j].bw,
                            bandId = list[j].band_id;
                        if (index < trs - 1) {
                            $('.table tbody tr').eq(j + 1).attr({
                                "data-roomid": roomId,
                                "data-bandid": bandId
                            }).html('<td>' + location + '</td><td>' + bandWidth + '</td><td class="text-center"><i class="fa fa-minus-circle remove-item"></i></td>');
                        } else {
                            $(".table tbody").append('<tr data-roomid="' + roomId + '" data-bandid="' + bandId + '"><td>' + location + '</td><td>' + bandWidth + '</td><td class="text-center"><i class="fa fa-minus-circle remove-item"></i></td></tr>');
                        }
                    }

                }
            }

            //动态标题
            var title = GetQueryString("departAlias") + "&nbsp;&nbsp;&nbsp;二线值班报告";//如果编辑状态的话应该放在ajax success回调的方法下
            $('.title-text').html(title);

            ue.focus();
            //执行添加按钮
            $(document).on('click', '.operate-add-btn', function () {
                var location = $('#selectPosition option:selected').val(), bandWidth = $('#inputBandwidth').val(),
                    roomId = $("#selectPosition option:selected").attr("data-roomid");
                if (location && bandWidth && location.length > 0 && String(bandWidth).length > 0 && !location.match(/^[ ]+$/) && !bandWidth.match(/^[ ]+$/)) {
                    var bandW = Number(bandWidth);
                    if (index < trs - 1) {//trs是表格固定的length长度,total是表格目前存在的数据条数(index)
                        //清空数据
                        $('#selectPosition').val('');
                        $('#inputBandwidth').val('');
                        var change_trs = $(".table tr").length;//可变的表格条数
                        if (change_trs - 1 > index) {
                            $('.table tbody tr').eq(index + 1).attr("data-roomid", roomId).html('<td>' + location + '</td><td>' + bandWidth + '</td><td class="text-center"><i class="fa fa-minus-circle remove-item"></i></td>');
                        } else {
                            $(".table tbody").append('<tr data-roomid="' + roomId + '"><td>' + location + '</td><td>' + bandWidth + '</td><td class="text-center"><i class="fa fa-minus-circle remove-item"></i></td></tr>');
                        }
                        index++;
                        total++;

                    } else {
                        //清空数据
                        $('#selectPosition').val('');
                        $('#inputBandwidth').val('');
                        var str = '<tr data-roomid="' + roomId + '"><td>' + location + '</td><td>' + bandWidth + '</td><td class="text-center"><i class="fa fa-minus-circle remove-item"></i></td></tr>';
                        $('.table tbody').append(str);
                        total++;

                    }
                } else {
                    $.myAlert({title: "错误信息", message: "参数请提交完整!"});
                }

            });

            //执行提交操作
            $('.btn-submit-confirm').click(function () {
                var departId = GetQueryString('departId'), departName = GetQueryString('departName'), data = {},
                    datalist = {}, datalist2 = [], dutyTime = $("#dutyTime").val();
                //获取表格数据
                var table = $('.table tbody tr');
                for (var i = 0; i < total; i++) {
                    datalist2.push({
                        idc: $(table[i + 1]).find('td').eq(0).html(),
                        bw: $(table[i + 1]).find('td').eq(1).html(),
                        room_id: parseInt($(table[i + 1]).attr("data-roomid"))
                    });

                    if (!$(table[i + 1]).attr("data-bandid")) {
                        addArray.push({
                            idc: $(table[i + 1]).find('td').eq(0).html(),
                            bw: $(table[i + 1]).find('td').eq(1).html(),
                            room_id: parseInt($(table[i + 1]).attr("data-roomid"))
                        });
                    }
                }
                //判断是否日报时间为空
                if (!dutyTime || dutyTime.length === 0) {
                    $.myAlert({title: ' 出错提示', message: '请填写日报时间！'});
                    return false;
                }
                //获取富文本编辑器内容
                var u_content = ue.getContent();
                //判断传的值是否全为空
                if (u_content.length === 0) {
                    $.myAlert({title: '出错提示', message: '请完善富文本框内容！'});
                    return;
                }
                if (dutyId) {//修改

                    data = {
                        "type": "edit",
                        "dutyId": dutyId,
                        "departId": departId,
                        "datalist": {
                            delete: deleteArray,
                            plus: addArray
                        },
                        "departName": departName,
                        "substance": u_content,
                        "level": 2,
                        "richTextTime": dutyTime  //新加字段
                    };
                } else {
                    data = {
                        "type": "create",
                        "departId": departId,
                        "datalist": datalist2,
                        "departName": departName,
                        "substance": u_content,
                        "level": 2,
                        "richTextTime": dutyTime  //新加字段
                    };
                }

                $.ajax({
                    type: 'POST',
                    url: '/datasave',
                    contentType: "application/x-www-form-urlencoded; charset=utf-8",
                    data: JSON.stringify(data),
                    success: function (data) {
                        if (data.code === 0) {//提交成功
                            var dutyId = GetQueryString("dutyId") || data.dutyId, title = GetQueryString('departAlias'),
                                dutyTime = data.richTextTime;
                            window.location.href = '/views?dutyId=' + dutyId + '&departId=' + departId + '&departAlias=' + title + '&duty_time=' + dutyTime;
                        } else if (data.code === 1) {

                            $.myAlert({title: '出错提示', message: data.errmessage});
                        }
                    },
                    error: function (err) {
                        $.myAlert({title: '出错提示', message: err.errmessage});
                    }
                });
            });


            $(document).on("click", ".remove-item", function () {
                var cur_parentobj = $(this).closest("tr"), cur_bandid = cur_parentobj.attr("data-bandid");
                if (dutyId && cur_bandid) {//编辑状态---删除上次提交的数据
                    deleteArray.push(parseInt(cur_bandid))
                }
                cur_parentobj.remove();
                //当前表格中数据减少一条
                index--;
                total--;
            });

            function loadComputerRoom() {
                ajaxRequest('GET', '/engineroom', {}, success, error, '{{ csrf_token }}');
                function success(data) {
                    var str = '<option data-roomid="0" >--请选择--</option>';
                    for (var i = 0; i < data.length; i++) {
                        var item = data[i];
                        str += '<option data-roomid="' + item.room_id + '" data-roomname="' + item.room_name + '">' + item.room_alias + '</option>';
                    }
                    $('#selectPosition').html(str);
                }

                function error(ero) {
                    $.myAlert({title: '出错提示', message: '请求出错！'});
                }
            }

            $(document).on("click", ".cancel-return", function () {
                window.history.go(-1);
            });
        });
    </script>
{% endblock %}